package main

import (
	"fmt"
	"sync"
	"sync/atomic"
)

type config struct {
	a []int
}

func (c *config) T() {}

//普通的版本，会出现错误不连续
func mainByCommon() {
	cfg := &config{}

	go func() {
		i := 0
		for {
			i++
			cfg.a = []int{i, i + 1, i + 2, i + 3, i + 4, i + 5}
		}
	}()

	var wg sync.WaitGroup
	for n := 0; n < 4; n++ {
		wg.Add(1)
		go func() {
			for n := 0; n < 100; n++ {
				fmt.Printf("%v\n", cfg)
			}
			wg.Done()
		}()
	}
	wg.Wait()
}

//atomic版本
func mainByAtomic() {
	var v atomic.Value
	v.Store(&config{})

	go func() {
		i := 0
		for {
			i++
			cfg := &config{a: []int{i, i + 1, i + 2, i + 3, i + 4, i + 5}}
			v.Store(cfg)
		}
	}()

	var wg sync.WaitGroup
	for n := 0; n < 4; n++ {
		wg.Add(1)
		go func() {
			for n := 0; n < 100; n++ {
				cfg := v.Load().(*config)
				cfg.T()
				fmt.Printf("%v\n", cfg)
			}
			wg.Done()
		}()
	}
	wg.Wait()
}

//读写锁的版本
func mainByLock() {
	var l sync.RWMutex
	var cfg *config

	go func() {
		i := 0
		for {
			i++
			l.Lock()
			cfg = &config{a: []int{i, i + 1, i + 2, i + 3, i + 4, i + 5}}
			l.Unlock()
		}
	}()

	var wg sync.WaitGroup
	for n := 0; n < 4; n++ {
		wg.Add(1)
		go func() {
			for n := 0; n < 100; n++ {
				l.RLock()
				cfg.T()
				l.RUnlock()
				fmt.Printf("%v\n", cfg)
			}
			wg.Done()
		}()
	}
	wg.Wait()
}

func main() {
	//mainByCommon()
	//mainByAtomic()
	mainByLock()
}
